package pers.hl.module_main.mine

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import kotlinx.android.synthetic.main.item_rv_book.view.*
import pers.hl.common.base.ext.showMessage
import pers.hl.lib_global.common.GlideUtils
import pers.hl.lib_global.model.bean.Book
import pers.hl.lib_global.model.bean.BookBorRec
import pers.hl.lib_global.model.enums.BookStatus
import pers.hl.module_main.BaseTitleRvFragment
import pers.hl.module_main.R
import pers.hl.module_main.common.BaseLibQuickAdapter
import pers.hl.module_main.common.ConfirmDialog
import pers.hl.module_main.common.SwipeMenuHelper

class MyBorrowFragment: BaseTitleRvFragment<BookBorRec>() {

    override fun createAdapter(): BaseLibQuickAdapter<BookBorRec, BaseViewHolder> {
        return object : BaseLibQuickAdapter<BookBorRec, BaseViewHolder>(R.layout.item_rv_book) {
            override fun convert(holder: BaseViewHolder, item: BookBorRec) {
                val data = item.book
                val ivSearchBook = holder.itemView.ivSearchBook
                data?.apply {
                    GlideUtils.loadBookImage(ivSearchBook.context, ivSearchBook, data)
                    holder.itemView.tvBookName.text = data.bookName
                    val subTitle = String.format(
                        "%s",
                        if (TextUtils.isEmpty(data.bookAuthor)) "佚名" else data.bookAuthor
                    )
                    holder.itemView.apply {
                        tvSearchSubtitle.text = subTitle
                        tvTime.text = TimeUtils.date2String(item.bbrTime)
                        item.book?.apply {
                            tvStatus.text = item.bbrStatus?.let { getStatusName(it) }
                        }
                        item.expiringDays?.let {
                            if (it <= 5) {
                                if (it < 0) {
                                    tvStatus.text = String.format("逾期%s天", -it)
                                } else {
                                    tvStatus.text = String.format("剩余%s天", it)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun getStatusName(bookStatus: Int): String {
        return BookStatus.getValueStr(bookStatus)
    }

    override fun beforeSetAdapter() {
        mBinding.apply {
            val creator = SwipeMenuHelper.createRightItem(mContext, "取消")
            recyclerView.setSwipeMenuCreator(creator)
            recyclerView.setOnItemMenuClickListener { menuBridge, adapterPosition ->

                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu()
                val item = mAdapter.getItem(adapterPosition) as BookBorRec
                val data = item.book
                if (data?.bookStatus != Book.STATUS_BORROWING) {
                    showMessage("当前状态不可取消")
                    return@setOnItemMenuClickListener
                }
                ConfirmDialog.create(mContext)
                    .content("您确定要取消借阅吗？")
                    .setConfirmListener {
                        item.bbrId?.let {
                            mViewModel.cancelBorrow(it).observe(this@MyBorrowFragment, Observer {
                                showMessage("取消成功")
                                getAllData()
                            })
                        }
                    }
                    .setCancelListener {  }
                    .show()
            }
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        getAllData()
    }

    private fun getAllData() {
        mViewModel.fetchMyBorrows().observe(this, Observer {
            if (it == null || it.isEmpty()) {
                mAdapter.setEmptyView()
            } else {
                mAdapter.setList(it)
                hideUnnecessaryMenu()
            }
        })
    }

    override fun getTitle(): String {
        return "我的借阅"
    }

    override fun hideUnnecessaryMenu() {
        val dataList = mAdapter.data
        dataList.forEachIndexed(action = { index, bookShareRec ->
            if (bookShareRec.bbrStatus != Book.STATUS_BORROWING) {
                hideMenu(index)
            }
        })
    }

}